package rocky.freemanagementsystemserver.config

import org.apache.shiro.mgt.SecurityManager
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor
import org.apache.shiro.spring.web.ShiroFilterFactoryBean
import org.apache.shiro.web.mgt.DefaultWebSecurityManager
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import rocky.freemanagementsystemserver.bean.CustomRealm


@Configuration
class ShiroConfig {

    @Bean
    @ConditionalOnMissingBean
    fun defaultAdvisorAutoProxyCreator(): DefaultAdvisorAutoProxyCreator? {
        val defaultAAP = DefaultAdvisorAutoProxyCreator()
        defaultAAP.isProxyTargetClass = true
        return defaultAAP
    }

    //将自己的验证方式加入容器
    @Bean
    fun myShiroRealm(): CustomRealm? {
        return CustomRealm()
    }

    //权限管理，配置主要是Realm的管理认证
    @Bean
    fun securityManager(): SecurityManager? {
        val securityManager = DefaultWebSecurityManager()
        securityManager.setRealm(myShiroRealm())
        return securityManager
    }

    //Filter工厂，设置对应的过滤条件和跳转条件
    @Bean
    fun shiroFilterFactoryBean(securityManager: SecurityManager?): ShiroFilterFactoryBean? {
        val shiroFilterFactoryBean = ShiroFilterFactoryBean()
        shiroFilterFactoryBean.securityManager = securityManager
        val map: MutableMap<String, String> = HashMap()
        //登出
        map["/logout"] = "logout"
//        map["/login"] = "anon";
        //对所有用户认证
        map["/**"] = "authc"

        //登录
        shiroFilterFactoryBean.loginUrl = "/token"
        //首页
        shiroFilterFactoryBean.successUrl = "/index"
        //错误页面，认证不通过跳转
        shiroFilterFactoryBean.unauthorizedUrl = "/error"
        shiroFilterFactoryBean.filterChainDefinitionMap = map
        return shiroFilterFactoryBean
    }


    @Bean
    fun authorizationAttributeSourceAdvisor(securityManager: SecurityManager?): AuthorizationAttributeSourceAdvisor? {
        val authorizationAttributeSourceAdvisor = AuthorizationAttributeSourceAdvisor()
        authorizationAttributeSourceAdvisor.securityManager = securityManager
        return authorizationAttributeSourceAdvisor
    }
}